import {Injectable} from "@angular/core";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Http} from "@angular/http";
import {UrlData} from "../../common/urldata";
import {Observable} from "rxjs/Observable";
import {LoginFormData} from "../../pages/login/login.form.data";
import {ExceptionHandler} from "../../common/exception.handler";

@Injectable()
export class UserService {

  constructor(private http: Http, private urlData: UrlData, private exceptionHandler: ExceptionHandler) {
  }

  logout(oauthToken: string): Observable<any> {
    return this.http
      .post(this.urlData.baseUrl + `v1/logout`, {token: oauthToken})
      .map(response => response.json())
      .catch(err => this.exceptionHandler.handleError(err));
  };

  login(loginFormData: LoginFormData): Observable<any> {
    return this.http
      .post(this.urlData.baseUrl + `v1/login`, loginFormData)
      .map(response => response.json())
      .catch(err => this.exceptionHandler.handleError(err));
  };

  registerDataValidate(data: any): any {
    if (!(/^1\d{10}$/.test(data.cellphone))) {
      return {
        status: false,
        msg: "请输入正确的手机号"
      };
    }
    if (!data.password || data.password.length > 20) {
      return {
        status: false,
        msg: "请输入20字符以内的密码"
      };
    }

    if (!data.invitationCode) {
      return {
        status: false,
        msg: "请输入邀请码"
      };
    }

    if (!data.verificationCode) {
      return {
        status: false,
        msg: "请输入验证码"
      };
    }
    return {
      status: true,
      msg: ""
    };
  }

  register(registerData: any) {
    return this.http
      .post(this.urlData.baseUrl + `v1/register`, registerData)
      .map(response => response.json())
      .catch(err => this.exceptionHandler.handleError(err));
  }

  personalCenter(param: { token: string }) {
    return this.http
      .get(this.urlData.baseUrl + `v1/personal/center/info/` + param.token)
      .map(response => response.json())
      .catch(err => this.exceptionHandler.handleError(err));
  }

  changePhoto(token: string, param: any) {
    return this.http
      .post(this.urlData.baseUrl + `v1/user/info/photo/` + token, param)
      .map(response => response.json())
      .catch(err => this.exceptionHandler.handleError(err));
  }
}
